package com.hjx.windowtool.fc2;

import java.awt.EventQueue;

import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
import javax.swing.UIManager;

import org.jsoup.Connection;
import org.jsoup.Connection.Response;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.hjx.windowtool.db.Tool;
import com.hjx.windowtool.tablemodel.CheckBoxCellRenderer;
import com.hjx.windowtool.tablemodel.MapTableModel;
import com.hjx.windowtool.util.JsoupTorrentSearch;
import com.hjx.windowtool.util.StrUtil;

import javax.swing.JButton;
import java.awt.FlowLayout;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import java.awt.event.ActionEvent;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JMenuBar;
import javax.swing.JMenu;
import javax.swing.JMenuItem;
import javax.swing.ListSelectionModel;

@Tool("FC2视频查找")
public class Fc2MovieFindApp {

	private static final String FC2_MOVIES_INDO = "fc2MoviesIndo";
	private JFrame frame;
	private JTextField txt_url;
	private JTextField txt_pages;
	private JTable table;
	private MapTableModel dm;
	private JLabel lbl_msg;

	/**
	 * Launch the application.
	 */
	public static void main(String[] args) {
		EventQueue.invokeLater(new Runnable() {
			public void run() {
				try {
					UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
					Fc2MovieFindApp window = new Fc2MovieFindApp();
					window.frame.setVisible(true);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		});
	}

	/**
	 * Create the application.
	 */
	public Fc2MovieFindApp() {
		initialize();
	}

	/**
	 * Initialize the contents of the frame.
	 */
	private void initialize() {
		frame = new JFrame();
		frame.setBounds(100, 100, 798, 507);
		frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		
		JPanel panel = new JPanel();
		frame.getContentPane().add(panel, BorderLayout.NORTH);
		
		JLabel label = new JLabel("地址");
		panel.add(label);
		
		txt_url = new JTextField();
		txt_url.setText("https://adult.contents.fc2.com/users/cospaco/");
		panel.add(txt_url);
		txt_url.setColumns(50);
		
		JButton button = new JButton("搜索");
		button.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				int showConfirmDialog = JOptionPane.showConfirmDialog(frame, "确认重新搜索？");
				if (showConfirmDialog!=0) {
					return;
				}
				search(txt_url.getText());
			}
		});
		
		JLabel label_2 = new JLabel("页数");
		panel.add(label_2);
		
		txt_pages = new JTextField();
		txt_pages.setText("13");
		panel.add(txt_pages);
		txt_pages.setColumns(10);
		panel.add(button);
		
		JButton button_1 = new JButton("载入");
		button_1.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				List<Map<String, String>> list = (List<Map<String, String>>) StrUtil.readObject(FC2_MOVIES_INDO);
				list.sort(new Comparator<Map<String, String>>() {
					@Override
					public int compare(Map<String, String> o1, Map<String, String> o2) {
						try {
							return Integer.valueOf(o2.get("id")).compareTo(Integer.valueOf(o1.get("id")));
						} catch (NumberFormatException e) {
							return o2.get("id").compareTo(o1.get("id"));
						}
					}
				});
				dm.setList(list);
				StrUtil.saveObject(FC2_MOVIES_INDO, list);
			}
		});
		panel.add(button_1);
		
		JButton button_2 = new JButton("查找磁力链");
		button_2.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				searchEdk();
			}
		});
		panel.add(button_2);
		
		JPanel panel_1 = new JPanel();
		frame.getContentPane().add(panel_1, BorderLayout.CENTER);
		panel_1.setLayout(new BorderLayout(0, 0));
		
		JScrollPane scrollPane = new JScrollPane();
		panel_1.add(scrollPane, BorderLayout.CENTER);
		
		dm = new MapTableModel(new ArrayList<>(), new String[] {"id","名称","发布时间","播放时间","影片id","详情地址","磁力链"},
				new String[] {"id","id","createTime","playTime","mid","url","edk"});
		table = new JTable(dm);
		table.setSelectionMode(ListSelectionModel.MULTIPLE_INTERVAL_SELECTION);
		table.setCellSelectionEnabled(true);
		table.getTableHeader().setDefaultRenderer(new CheckBoxCellRenderer(table));
		table.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseClicked(MouseEvent e) {
				if (e.getClickCount()==1) {
					Class<?> columnClass = dm.getColumnClass(table.getSelectedColumn());
					if (columnClass.equals(Boolean.class)) {
						int selectedRow = table.getSelectedRow();
						dm.getList().get(selectedRow).put("checked", !Boolean.valueOf(dm.getList().get(selectedRow).get("checked"))+"");
						dm.fireTableDataChanged();
					}
				}
			}
		});
		scrollPane.setViewportView(table);
		
		JPanel panel_2 = new JPanel();
		frame.getContentPane().add(panel_2, BorderLayout.SOUTH);
		panel_2.setLayout(new BorderLayout(0, 0));
		
		lbl_msg = new JLabel("状态");
		panel_2.add(lbl_msg);
		
		JMenuBar menuBar = new JMenuBar();
		frame.setJMenuBar(menuBar);
		
		JMenu menu = new JMenu("菜单");
		menuBar.add(menu);
		
		JMenuItem mntmtorrentkittycookie = new JMenuItem("加载header");
		mntmtorrentkittycookie.addActionListener(new ActionListener() {
			public void actionPerformed(ActionEvent e) {
				JsoupTorrentSearch.loadJsoupHeader();
			}
		});
		menu.add(mntmtorrentkittycookie);
		HashMap<String, String> e = new HashMap<>();
		e.put("id", "1");
		dm.getList().add(e);
		dm.fireTableDataChanged();
	}

	protected void searchEdk() {
		Runnable runnable = new Runnable() {
			public void run() {
				List<Map<String,String>> list = dm.getList().stream().filter(e->"true".equals(e.get("checked"))).collect(Collectors.toList());
				System.out.println(list.size());
				if (list.isEmpty()) {
					return;
				}
				for (int i =0;i<dm.getList().size();i++) {
					Map<String, String> map = dm.getList().get(i);
					System.out.println(i+"=="+map.get("checked"));
					if (!"true".equals(map.get("checked"))) {
						continue;
					}
					if (map.get("edk")!=null&&!map.get("edk").trim().isEmpty()) {
						continue;
					}
					String megnet=null;
					try {
						megnet = JsoupTorrentSearch.getMegnetByCntorrentkitty(map.get("mid"));
					} catch (Exception e) {
						e.printStackTrace();
					}
					if (megnet==null) {
						try {
							megnet=JsoupTorrentSearch.getMegnetByBtFeifeibt(map.get("mid"));
						} catch (Exception e) {
							e.printStackTrace();
						}
					}
					
					if (megnet == null) {
						try {
							megnet = JsoupTorrentSearch.getMegnetByBtyunsou(map.get("mid"));
						} catch (IOException e) {
							e.printStackTrace();
						}
					}
					System.out.println(map.get("id")+"="+megnet);
					if (megnet != null) {
						map.put("edk", megnet);
						dm.fireTableDataChanged();
					}
				}
				save();
				JOptionPane.showMessageDialog(frame, "查找完成");
			}
		};
		new Thread(runnable).start();
	}

	protected void search(String indexurl) {
		try {
			Map<String,Map<String, String>> listInfo=new HashMap<>();
			for (int i = 1; i <= Integer.valueOf(txt_pages.getText()); i++) {
				String url=indexurl;
				if (i>1) {
					url+="?&page="+i;
				}
				System.out.println(url);
				Connection conn = Jsoup.connect(url);
				Document document = conn.get();
				//			System.out.println(document);
				Elements elementsByClass = document.getElementsByClass("sell_block");
				for (Element element : elementsByClass) {
					Element element2 = element.getElementsByTag("a").get(1);
					String surl = element2.attr("abs:href");
					Map<String,String> map = new HashMap<>();
					map.put("url", surl);
					map.put("sname", element2.text());
					String id = surl.substring(surl.lastIndexOf("=")+1);
					map.put("mid", "fc2 "+id);
					map.put("id",id);
//					System.out.println(map.get("mid")+"==="+surl + "===name=" + element2.text());
					if (listInfo.containsKey(id)) {
						continue;
					}
					listInfo.put(id,map);
					boolean b = getDetailInfo(map,surl);
					for (int j = 0; j < 3&&!b; j++) {
						b = getDetailInfo(map,surl);
					}
				} 
			}
			System.out.println("获取列表完成");
			ArrayList<Map<String, String>> list = new ArrayList<>(listInfo.values());
			list.sort(new Comparator<Map<String, String>>() {
				@Override
				public int compare(Map<String, String> o1, Map<String, String> o2) {
					return o2.get("id").compareTo(o1.get("id"));
				}
			});
			dm.setList(list);
			save();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private void save() {
		StrUtil.saveObject(FC2_MOVIES_INDO, dm.getList());
	}

	private boolean getDetailInfo(Map<String, String> map, String surl) {
		try {
			Document document2 = Jsoup.connect(surl).get();
			map.put("name", document2.select("h2[class=title_bar]").get(0).text());
			Elements select = document2.select("div[class=main_info_block]");
			Elements elementsByTag = select.get(0).getElementsByTag("dd");
			
			map.put("createTime", elementsByTag.get(elementsByTag.size()==5?2:3).text());
			map.put("playTime", elementsByTag.get(elementsByTag.size()==5?4:5).text());
			return true;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return false;
	}

}
